﻿using System;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using BrasilFramework.Controle.Silverlight.Comum;

namespace BrasilFramework.Controle.Silverlight
{

    /// <summary>
    /// Extensão do <see cref="DatePicker"/> com remoção da marca d'água e formatação ao digitar.
    /// </summary>
    public class Calendario : DatePicker
    {
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            DatePickerTextBox controleTexto = (DatePickerTextBox)GetTemplateChild("TextBox");
            controleTexto.MaxLength = 10;
            controleTexto.Watermark = string.Empty;
            controleTexto.KeyDown += EventoTeclado.CampoApenasNumero;
            controleTexto.KeyUp += FormatarData;
            controleTexto.LostFocus += Validar;
            controleTexto.GotFocus += LimparMarcaDAgua;
        }

        private void LimparMarcaDAgua(object sender, System.Windows.RoutedEventArgs e)
        {
            DatePickerTextBox controleTexto = (DatePickerTextBox)sender;
            Dispatcher.BeginInvoke(() => controleTexto.Watermark = string.Empty);
        }

        private void Validar(object sender, System.Windows.RoutedEventArgs e)
        {
            DatePickerTextBox controleTexto = (DatePickerTextBox)sender;
            DateTime data;
            if(!DateTime.TryParse(controleTexto.Text, out data)) controleTexto.Text = string.Empty;
            Dispatcher.BeginInvoke(()=> controleTexto.Watermark = string.Empty);
        }

        private void FormatarData(object sender, KeyEventArgs e)
        {
            DatePickerTextBox controleTexto = (DatePickerTextBox) sender;
            controleTexto.Text = EventoTeclado.Formatar(controleTexto.Text, "##/##/####");
            controleTexto.SelectionStart = controleTexto.Text.Length;
            Dispatcher.BeginInvoke(() => controleTexto.Watermark = string.Empty);
        }
    }
}